package com.github.data_manage.controller

import cn.dev33.satoken.stp.StpUtil
import com.github.data_manage.common.CommonResult
import com.github.data_manage.common.ResultCode
import com.github.data_manage.config.SystemException
import com.github.data_manage.dao.UserDao
import com.github.data_manage.domain.po.User
import com.github.data_manage.domain.vo.UserLoginVo
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 *@author CHN
 *@since 2024-08-18 16:28
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "AuthController", description = "用户登录")
class AuthController(private val userDao: UserDao) {

    @PostMapping("/login")
    @Operation(description = "登录")
    fun login(@Valid @RequestBody userLoginVo: UserLoginVo): CommonResult<String?> {
        val user =
            userDao.findByName(userLoginVo.name).orElseThrow { SystemException("用户${userLoginVo.name}不存在") }
        if (user.password.equals(userLoginVo.password)) {
            StpUtil.login(user.id!!)
            val tokenValue = StpUtil.getTokenValue()
            return CommonResult.success(tokenValue)
        }
        return CommonResult.failed("账号名或密码错误")
    }

    @GetMapping("/currentUser")
    @Operation(description = "查询当前登陆的用户")
    fun currentUserInfo(): CommonResult<Any>{
        val userId = StpUtil.getLoginIdAsInt()
        return CommonResult.success(userDao.findById(userId).get())
    }

    @DeleteMapping("/logout")
    @Operation(description = "退出登录")
    fun logout(): CommonResult<String> {
        StpUtil.logout()
        return CommonResult.success(ResultCode.SUCCESS.message)
    }


}